#!/usr/bin/python
"""
Cleans up script filenames/versions from Emerald-exported names to be suitable for checking into svn

USAGE: type 'ocdeversion srcdir destdir' in the command line, where srcdir is a folder containing the ugly filenames, and destdir is the folder where you would like the cleaned-up ones copied.
"""

import sys
import os
import urllib
import re

try:
  src = sys.argv[1]
  dest = sys.argv[2]
except IndexError:
  print __doc__
  sys.exit()

if not os.path.isdir(src):
  print "error: %s is not a directory" % src
  sys.exit()

if not os.path.isdir(dest):
  print "error: %s is not a directory" % dest
  sys.exit()

files = os.listdir(src)

#compiling this regex outside the loop so we don't do it over and over unnecessarily
versionpattern = re.compile("^//Open.*? - \d\.\d\d\d$")#match "//OpenCollar - leash - 3.334.  

for file in files:
  #only do .lsltext files
  unquoted = urllib.unquote(file)
  if unquoted.startswith("Open") and unquoted.endswith(".lsltext"):
    #OC filenames are in format "OpenCollar - menu - 3.334
    name_version = unquoted[:-8]#strip off the ".lsltext" 
    contents = open(src + "/" + file, 'r').read().splitlines()
    #now see if first line already has version info.  if so, replace.  if not, prepend
    firstline = contents[0]
    if versionpattern.match(firstline):
      #this file has version info on first line.  overwrite it
      contents[0] = "//" + name_version
      print "updating version info in %s" % name_version
    else:
      #no version info found on first line, prepend it
      contents = ["//" + name_version] + contents
      print "adding version info to %s" % name_version
    #save file without version number
    destfile = dest + "/" + name_version[:-8] + ".lsl"
    try:
      newfile = open(destfile, "w")
      newfile.write("\n".join(contents))
    except IOError:
      print "Could not write " + destfile